package com.jthinker.dao.impl;

import com.jthinker.bean.vo.QueryResult;
import com.jthinker.bean.vo.SearchFilter;
import com.jthinker.dao.BaseDao;
import com.jthinker.dao.ResourceDao;
import com.jthinker.bean.enu.ResourceType;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by chen.gang on 2015/2/10.
 */
@Repository
public class ResourceDaoImpl implements ResourceDao
{
    @Resource
    private BaseDao baseDao;

    @Override
    public Map<String, Object> findOne(Long resourceId)
    {
        return baseDao.read("SELECT * FROM sys_resource WHERE id =?", resourceId);
    }

    @Override
    public List<Map<String, Object>> findAll()
    {
        return baseDao
                .query("SELECT id, NAME, TYPE, url, permission, parent_id, parent_ids, available FROM sys_resource ORDER BY CONCAT(parent_ids, id) ASC");
    }

    @Override
    public QueryResult<Map<String, Object>> query(SearchFilter filter)
    {
        StringBuilder sql = new StringBuilder("SELECT * FROM sys_resource WHERE type = ?");
        Integer total = baseDao.queryTotal(sql.toString(), ResourceType.MENU.getKey());
        if (total == null || total.intValue() == 0)
        {
            return QueryResult.empty();
        }

        List<Map<String, Object>> data = baseDao
                .queryPagination(sql.toString(), filter.getPage(), filter.getPageSize(), ResourceType.MENU.getKey());
        return new QueryResult<Map<String, Object>>(total, data, filter.getPage(), filter.getPageSize());
    }

    @Override
    public void create(Map<String, Object> record) throws Exception
    {
        baseDao.insert("sys_resource", record);
    }
}
